namespace Test.ConsoleProgram.Algorithm.Solution
{
    [TestDescription("算法: 0404. 左叶子之和")]
    public class No0404_SumOfLeftLeaves : AbsBaseTestItem
    {
        public class TreeNode
        {
            public int val;
            public TreeNode left;
            public TreeNode right;
            public TreeNode(int x) { val = x; }
        }

        /*
        计算给定二叉树的所有左叶子之和。
        */

        public override void OnTest()
        {
            Assert.TestExe(SumOfLeftLeaves,
                new TreeNode(3)
                {
                    left = new TreeNode(9),
                    right = new TreeNode(20)
                    {
                        left = new TreeNode(15),
                        right = new TreeNode(7),
                    },
                }, 24);
        }

        public int SumOfLeftLeaves(TreeNode root)
        {
            if (root == null) return 0;
            int sum = SumOfLeftLeaves(root.left);
            sum += SumOfLeftLeaves(root.right);
            var left = root.left;
            sum += (left != null && left.left == null && left.right == null) ? root.left.val : 0;
            return sum;
        }
    }
}
